#include<func.h>

void clean(void *p)
{
    printf("cleaning\n");
    free(p);
}

void *func(void *p)
{
    printf("child thread:\n");
    char *tmp = (char*)malloc(20);//申请内存
    pthread_cleanup_push(clean,tmp);
    
    printf("child thread:read is coming\n");
    read(0,tmp,5);//卡在read处，并从这里cancel
    printf("after read\n");
    pthread_exit((void*)1);
    pthread_cleanup_pop(0);
}

int main()
{
    pthread_t pthid;
    int ret;
    ret = pthread_create(&pthid,NULL,func,NULL);
    THREAD_ERROR_CHECK(ret,"pthread_create");
    printf("main thread sleeping\n");
    sleep(3);
    printf("main thread wake up, cancel child thread\n");
    pthread_cancel(pthid);
   
    long threadRet;
    pthread_join(pthid,(void**)&threadRet);
    printf("child exit code:%ld\n",threadRet);

    return 0;
}
